﻿using MediatR;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.MenuCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Request;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.MenuHandler
{
    public class MenuShowCommandHandlers : IRequestHandler<MenuShowCommand, ApiResult<PagingDto>>
    {
        private readonly IMenuRepository _menuRepository;
        private readonly ILogger<MenuShowCommandHandlers> _logger;
        public MenuShowCommandHandlers(IMenuRepository menuRepository, ILogger<MenuShowCommandHandlers> logger)
        {
            _menuRepository = menuRepository;
            _logger = logger;
        }

        public async Task<ApiResult<PagingDto>> Handle(MenuShowCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var menus  = await _menuRepository.GetAllAsunc(x=>x.sys_id==request.sys_id&&x.del_flag==0);
                var list = from x in menus
                           select new
                           {
                               x.id,
                               x.menu_name,
                               x.menu_url,
                               x.menu_icon,
                               Pid= GetMenuHierarchy(menus,x),
                               x.order_num,
                               x.perms,
                               x.type,
                               x.create_date,
                               x.create_by,
                               x.update_date,
                               x.update_by,
                               x.remarks,
                           };
                var totalCount = list.Count();
                var totalPages = (int)Math.Ceiling(totalCount / (double)request.pageSize);
                var pagedMenus = list.OrderBy(x=>x.order_num).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                var pagingDto = new PagingDto
                {
                    TotalPage = totalPages,
                    TotalCount = totalCount,
                    List = pagedMenus
                };

                return new ApiResult<PagingDto>()
                {
                   
                    Data = pagingDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理菜单显示命令时发生错误");
                return new ApiResult<PagingDto>()
                {
                    Message = "处理菜单显示命令时发生错误,请稍后重试",
            
                };
            }
        }
        private static string GetMenuHierarchy(List<sys_menu> menus, sys_menu currentMenu)
        {
            if (currentMenu.parent_id == 0)
            {
                return currentMenu.menu_name;
            }
            else
            {
                var parentMenu = menus.FirstOrDefault(x => x.id == currentMenu.parent_id);
                if (parentMenu != null)
                {
                    var parentName = GetMenuHierarchy(menus, parentMenu);
                    return $"{parentName}>{currentMenu.menu_name}";
                }
                else
                {
                    return currentMenu.menu_name;
                }
            }
        }
    }
}
